//
//  LoginViewController.m
//  WindRunner
//
//  Created by leeqb on 9/29/14.
//  Copyright (c) 2014 poweropt. All rights reserved.
//

#import "LoginViewController.h"

@interface LoginViewController ()

@end

@implementation LoginViewController

- (id)initWithCoder:(NSCoder *)aDecoder
{
    self = [super initWithCoder:aDecoder];
    if(self) {
        self.navigationItem.hidesBackButton = YES;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = BACKGROUND_COLOR;
    self.registerButton.layer.cornerRadius = 4;
    self.loginButton.layer.cornerRadius = 4;
    self.buttonSina.layer.cornerRadius = 6;
    self.buttonSina.layer.masksToBounds = YES;
    self.userNameField.placeholder = LocalStringSecurity(@"LOGIN_PLACE_USERNAME");
    self.passField.placeholder = LocalStringSecurity(@"LOGIN_PLACE_PASSWORD");
    [_registerButton setTitle:LocalStringSecurity(@"BTN_TITLE_REGISTER") forState:UIControlStateNormal];
    [_loginButton setTitle:LocalStringSecurity(@"BTN_TITLE_LOGIN") forState:UIControlStateNormal];
    
    CGRect rect = CGRectZero;
    UIImage *iconUserName = [UIImage imageNamed:@"icon_username.png"];
    UIImage *iconPassword = [UIImage imageNamed:@"icon_password.png"];
    UIImage *bgImage35 = [UIImage imageNamed:@"bg_login480.png"];
    
    // 3.5寸背景图
    if([SCREEN_INCH isEqualToString:@"3.5"]) {
        rect = _bgImageView.frame;
        rect.origin.y = 3;
        rect.size.width = SCREEN_WIDTH;
        rect.size.height = SCREEN_HEIGHT;
        _bgImageView.frame = rect;
        _bgImageView.image = bgImage35;
        
        rect = _loginPanel.frame;
        rect.origin.y -= 20;
        _loginPanel.frame = rect;
    }
    
    rect = self.userNameField.frame;
    rect.origin.x = 0;
    rect.origin.y = 0;
    rect.size.width = iconUserName.size.width/2 + 20;
    UIView *leftView = [[UIView alloc] initWithFrame:rect];
    rect.origin.x = 10;
    rect.origin.y = (self.userNameField.frame.size.height - iconUserName.size.height/2) / 2;
    rect.size.width = iconUserName.size.width / 2;
    rect.size.height = iconUserName.size.height / 2;
    UIImageView *leftIconView = [[UIImageView alloc] initWithImage:iconUserName];
    leftIconView.frame = rect;
    [leftView addSubview:leftIconView];
    self.userNameField.leftViewMode = UITextFieldViewModeAlways;
    self.userNameField.leftView = leftView;
    
    rect = self.passField.frame;
    rect.origin.x = 0;
    rect.origin.y = 0;
    rect.size.width = iconPassword.size.width/2 + 20;
    leftView = [[UIView alloc] initWithFrame:rect];
    rect.origin.x = 10;
    rect.origin.y = (self.passField.frame.size.height - iconPassword.size.height/2) / 2;
    rect.size.width = iconPassword.size.width / 2;
    rect.size.height = iconPassword.size.height / 2;
    leftIconView = [[UIImageView alloc] initWithImage:iconPassword];
    leftIconView.frame = rect;
    [leftView addSubview:leftIconView];
    self.passField.leftViewMode = UITextFieldViewModeAlways;
    self.passField.leftView = leftView;
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.navigationController.navigationBarHidden = YES;
    self.navigationItem.title = LocalStringSecurity(@"NAV_TITLE_LOGIN");
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    // 在登录界面即将消失的时候将导航条显示出来，否则登录成功后看不到主页的导航条
    self.navigationController.navigationBarHidden = NO;
}

// 点击回车隐藏键盘
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    return YES;
}

- (IBAction)loginButtonClick:(UIButton *)sender {
    [self.userNameField resignFirstResponder];
    [self.passField resignFirstResponder];
    
    NSString *userName = [NSString formatString:self.userNameField.text];
    NSString *pass = [NSString formatString:self.passField.text];
    
    if([userName isEqualToString:@""]) {
        [FMToast showMessage:LocalStringSecurity(@"TOAST_NO_USERNAME")];
        return;
    }
    
    if([pass isEqualToString:@""]) {
        [FMToast showMessage:LocalStringSecurity(@"TOAST_NO_PASSWORD")];
        return;
    }
    
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    [params setValue:userName forKey:@"username"];
    [params setValue:pass forKey:@"pwd"];
    [params setValue:CURR_COORDINATE_X_STR forKey:@"locationX"];
    [params setValue:CURR_COORDINATE_Y_STR forKey:@"locationY"];
    FMRequestObject *requestObj = [[FMRequestObject alloc] init];
    requestObj.baseURL = BASE_API_URL_WINDRUNNER;
    requestObj.interface = @"login";
    requestObj.params = params;
    [FMToast showLoading:LocalStringCommon(@"OPER_DOING")];
    [FMNetwork request:requestObj showMask:NO success:^(NSDictionary *data) {
        if(![[EaseMob sharedInstance].chatManager isLoggedIn]) { // 未登录环信
            [[EaseMob sharedInstance].chatManager asyncLoginWithUsername:userName password:pass completion:^(NSDictionary *loginInfo, EMError *error) {
                [FMToast hide];
                if (!error && loginInfo) {
                    // 设置自动登录
                    /*
                     此属性如果被设置为YES, 会在以下几种情况下被重置为NO:
                     1. 用户发起的登出动作;
                     2. 用户在别的设备上更改了密码, 导致此设备上自动登陆失败;
                     3. 用户的账号被从服务器端删除;
                     4. 用户从另一个设备把当前设备上登陆的用户踢出.
                     */
                    [[EaseMob sharedInstance].chatManager setIsAutoLoginEnabled:YES];
                    
                    NSDictionary *record = data[@"record"];
                    if(record && ![record isEqual:[NSNull null]]) {
                        NSMutableDictionary *userinfo = [NSMutableDictionary dictionary];
                        for(NSString *key in record.allKeys) {
                            if([record[key] isEqual:[NSNull null]]) {
                                [userinfo setValue:@"" forKey:key];
                            } else {
                                [userinfo setValue:record[key] forKey:key];
                            }
                        }
                        [AuthHelper setCurrentUser:userinfo];
                    }
                    
                    [self.navigationController popToViewController:self.navigationController.viewControllers[0] animated:YES];
                } else {
                    [FMToast showMessage:LocalStringSecurity(@"TOAST_LOGIN_FAIL")];
                }
            } onQueue:nil];
        } else { // 已登录环信
            [FMToast hide];
            
            NSDictionary *record = data[@"record"];
            if(record && ![record isEqual:[NSNull null]]) {
                NSMutableDictionary *userinfo = [NSMutableDictionary dictionary];
                for(NSString *key in record.allKeys) {
                    if([record[key] isEqual:[NSNull null]]) {
                        [userinfo setValue:@"" forKey:key];
                    } else {
                        [userinfo setValue:record[key] forKey:key];
                    }
                }
                [AuthHelper setCurrentUser:userinfo];
            }
            
            [self.navigationController popToViewController:self.navigationController.viewControllers[0] animated:YES];
        }
    } falied:^(NSError *error) {
        [FMToast hide];
        [FMToast showMessage:LocalStringSecurity(@"TOAST_LOGIN_FAIL")];
        [AuthHelper onLoginFailed:error];
    }];
}

// 腾讯微博登陆
- (IBAction)loginWithTCWB:(id)sender {
    UMSocialSnsPlatform *snsPlatform = [UMSocialSnsPlatformManager getSocialPlatformWithName:UMShareToSina];
    snsPlatform.loginClickHandler(self,[UMSocialControllerService defaultControllerService],YES,^(UMSocialResponseEntity *response){
        // 获取微博用户名、uid、token等
        if (response.responseCode == UMSResponseCodeSuccess) {
            UMSocialAccountEntity *snsAccount = [[UMSocialAccountManager socialAccountDictionary] valueForKey:UMShareToSina];
            NSLog(@"username is %@, uid is %@, token is %@ url is %@",snsAccount.userName,snsAccount.usid,snsAccount.accessToken,snsAccount.iconURL);
        }
    });
}

// Facebook登录
- (IBAction)loginWithFacebook:(id)sender {
    UMSocialSnsPlatform *snsPlatform = [UMSocialSnsPlatformManager getSocialPlatformWithName:UMShareToFacebook];
    snsPlatform.loginClickHandler(self,[UMSocialControllerService defaultControllerService],YES,^(UMSocialResponseEntity *response) {
        //获取微博用户名、uid、token等
        if (response.responseCode == UMSResponseCodeSuccess) {
            UMSocialAccountEntity *snsAccount = [[UMSocialAccountManager socialAccountDictionary] valueForKey:UMShareToFacebook];
            NSLog(@"username is %@, uid is %@, token is %@ url is %@",snsAccount.userName,snsAccount.usid,snsAccount.accessToken,snsAccount.iconURL);
        }
    });
}

@end
